package com.sz.web.account.service.serviceImp;

import com.sz.web.account.entity.AccountUser;
import com.sz.web.account.enums.CodeName;
import com.sz.web.account.mapper.AccountUserMapper;
import com.sz.web.account.service.AccountUserService;
import com.sz.web.common.enums.SessionKey;
import com.sz.web.common.pojo.ReturnPojo;
import com.sz.web.common.service.serviceImp.BaseServiceImp;
import com.sz.web.util.Encript;
import com.sz.web.util.ReturnUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class AccountUserServiceImp extends BaseServiceImp<AccountUser> implements AccountUserService{


    @Resource
    private AccountUserMapper accountUserMapper;
    @Value("${web.login.VerificationCode}")
    String verificationCode;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpSession session;


    /**
     * 注册
     *
     * @param accountUser
     * @return
     */
    @Override
    public ReturnPojo register(AccountUser accountUser) {
        if (StringUtils.isEmpty(accountUser.getAccount())) {
            return ReturnUtil.fail("账户名不能为空");
        }
        if (StringUtils.isEmpty(accountUser.getPassword())) {
            return ReturnUtil.fail("密码不能为空");
        }
        return ReturnUtil.success(accountUser);
    }

    /**
     * 登录
     *
     * @param accountUser
     * @return
     */
    @Override
    public ReturnPojo login(AccountUser accountUser) {
        if (StringUtils.isEmpty(accountUser.getAccount())) {
            return ReturnUtil.fail("账户名不能为空");
        }
        if (StringUtils.isEmpty(accountUser.getPassword())) {
            return ReturnUtil.fail("密码不能为空");
        }
        String SessionCode = StringUtils.isEmpty(request.getSession().getAttribute(CodeName.Code.getName())) ? "" : String.valueOf(request.getSession().getAttribute(CodeName.Code.getName()));
        if (Boolean.valueOf(verificationCode)) {
            if (StringUtils.isEmpty(accountUser.getCode()) || !SessionCode.toUpperCase().equals(accountUser.getCode().toUpperCase())){
                return ReturnUtil.fail("验证码错误");
            }
        }
        AccountUser accountUserDb = accountUserMapper.selectByAccount(accountUser.getAccount());
        if (null == accountUserDb) {
            return ReturnUtil.fail("没有此账户");
        }
        if (!Encript.authenticatePassword(accountUserDb.getPassword(), accountUser.getPassword())) {
            return ReturnUtil.fail("密码不正确");
        }
        session.setAttribute(SessionKey.ACCOUNTINFO.getStrKey(),accountUserDb);
        session.setMaxInactiveInterval(3600);
        return ReturnUtil.success(accountUserDb);
    }

}
